﻿using System;
using NHibernate;

namespace TimeKeeper.Infrastructure
{
    public class CustomInterceptor : EmptyInterceptor
    {
        private readonly IEntityFactory _entityFactory;
        private ISession _session;

        public CustomInterceptor(IEntityFactory entityFactory)
        {
            _entityFactory = entityFactory;
        }

        public override String GetEntityName(Object entity)
        {
            return entity.GetType().Assembly.FullName.StartsWith("DynamicProxyGenAssembly2") == true ? (entity.GetType().BaseType.FullName) : (entity.GetType().FullName);
        }

        public override void SetSession(ISession session)
        {
            _session = session;
            base.SetSession(session);
        }

        public override Object Instantiate(String clazz, EntityMode entityMode, Object id)
        {
            if (entityMode == EntityMode.Poco)
            {
                var type = Type.GetType(clazz, false);

                if (type != null)
                {
                    var instance = _entityFactory.Create(type);
                    _session.SessionFactory.GetClassMetadata(clazz).SetIdentifier(instance, id, entityMode);
                    return instance;
                }
            }

            return (base.Instantiate(clazz, entityMode, id));
        }
    }
}

